/**
 * 
 */
package ca.biosample.robot.serial;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Mike Sokolsky
 *
 */
public class CopyOfRobotInterface {

	static final String COMM_PORT = "COM6";
	
	public SerialPort port;
	
	private InputStream in;
	private OutputStream out;
	
	static final byte[] BARCODE_START_READ = {
		0x21, 0x39, 0x39, 0x32, 0x35, 0x33,
		0x32, 0x32, 
		0x40, 0x40, 0x0D, 0x0A};
	
	//static final byte[] BARCODE_START_READ = {
	//	0x1B, 0x02, 0x53, 0x0D, 0x0A };
	/**
	 * 
	 * @param portName
	 */
	public CopyOfRobotInterface(String portName) {
		try {
			CommPortIdentifier cpi = CommPortIdentifier.getPortIdentifier(portName);
			CommPort cp = cpi.open(this.getClass().getName(), 2000);
			if(cp instanceof SerialPort) {
				port = (SerialPort) cp;
				port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
				port.setDTR(true);
				port.setRTS(true);
				port.setSerialPortParams(
						38400, 
						SerialPort.DATABITS_8, 
						SerialPort.STOPBITS_1,
						SerialPort.PARITY_NONE);
				port.setDTR(true);
				port.setRTS(true);
				in = port.getInputStream();
				(new Thread(new SerialReader(in))).start();
				out = port.getOutputStream();
				System.out.println("Opened port " + portName);
			}
			else {
				port = null;
				System.out.println("Port " + portName + " is not a COM port!");
			}
		} catch (NoSuchPortException e) {
			port = null;
			System.out.println("Port " + portName + " does not exist!");
		} catch (PortInUseException e) {
			port = null;
			System.out.println("Port " + portName + " is in use!");
		} catch (UnsupportedCommOperationException e) {
			port = null;
			System.out.println("Could not open " + portName + 
					" with correct settings.");
		} catch (IOException e) {
			port = null;
			System.out.println("Could not open " + portName + 
					" io streams.");
		}
	}
	
	public String readCode() {
		String response = "";
		try {
			System.out.println("Sending data...");
			out.write(BARCODE_START_READ);
			Thread.sleep(10000);
		} catch (IOException e) {
			System.out.println("Could not communicate with the serial port");
			return "";
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}
		return response;
	}
	/**
	 * @return
	 */
	private void openSerialPort() {
		

	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
	
		CopyOfRobotInterface reader = new CopyOfRobotInterface(COMM_PORT);
		if(reader.port == null)
			System.exit(1);
		while(true) {
			reader.readCode();
		}
	}

	public static class SerialReader implements Runnable 
	{
	    InputStream in;
	    
	    public SerialReader ( InputStream in )
	    {
	        this.in = in;
	    }
	    
	    public void run ()
	    {
	        byte[] buffer = new byte[1024];
	        int len = -1;
	        try
	        {
	            while ( ( len = this.in.read(buffer)) > -1 )
	            {
	                System.out.print(new String(buffer,0,len));
	            }
	        }
	        catch ( IOException e )
	        {
	            e.printStackTrace();
	        }            
	    }
	}
	
	public static class SerialWriter implements Runnable 
    {
        OutputStream out;
        
        public SerialWriter ( OutputStream out )
        {
            this.out = out;
        }
        
        public void run ()
        {
            try
            {                
                int c = 0;
                while ( ( c = System.in.read()) > -1 )
                {
                    this.out.write(c);
                }                
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }            
        }
    }

}



